#include "lnqueue.h"

PLQueue createQueue()
{
    PLQueue queue = (PLQueue) malloc(sizeof(struct stQueue));
    
    if (queue != NULL)
    {
        queue->head = NULL;
        queue->rear = NULL;
        queue->length = 0;
        
        return queue;
    }
    
    return NULL;
}

int enqueue(PLQueue queue, PBinTreeNode x)
{
    PNode p;
    if (queue == NULL)
    {
        return -1;
    }
    
    p = (PNode) malloc (sizeof(struct Node));
    if (p != NULL)
    {
        p->info = x;
        p->link = NULL;

        if (isEmpty(queue) != 1)
        {
            queue->rear->link = p;
            queue->rear = p;
        }
        else
        {
            queue->head = p;
            queue->rear = p;
        }
        
        queue->length = queue->length + 1;
        return 1;
    }
    
    return 0;
}

int dequeue(PLQueue queue)
{
    PNode p;
    if (queue == NULL)
    {
        return -1;
    }
    
    if (isEmpty(queue) != 1)
    {
        if (length(queue) > 1)
        {
            p = queue->head;
            queue->head = queue->head->link;
            free(p);
            queue->length = queue->length - 1;
        }
        else
        {
            p = queue->head;
            queue->head = NULL;
            queue->rear = NULL;
            free(p);
            queue->length = queue->length - 1;
        }
        return 1;
    }
    
    return 0;
}

int frontQueue(PLQueue queue, PBinTreeNode *x)
{
    if (queue == NULL)
    {
        return -1;
    }
    
    if (isEmpty(queue) != 1)
    {
        *x = queue->head->info;
        return 1;
    }
    
    return 0;
}

int length(PLQueue queue)
{
    if (queue == NULL)
    {
        return -1;
    }
    
    return queue->length;
}

int destroyQueue(PLQueue *queue)
{
    if (*queue == NULL)
    {
        return -1;
    }
    
    emptyQueue(*queue);
    free (*queue);
    *queue = NULL;
    return 1;
}

int emptyQueue(PLQueue queue)
{
    if (queue == NULL)
    {
        return -1;
    }
    
    while (isEmpty(queue) != 1)
    {
        dequeue(queue);
    }
    
    return 1;
}

int isEmpty(PLQueue queue)
{
    if (queue == NULL)
    {
        return -1;
    }
    
    if (queue->head == NULL)
    {
        return 1;
    }
    
    return 0;
}

int printQueue(PLQueue queue)
{
    PNode p;
    char buffer[100];

    if (queue == NULL)
    {
        return -1;
    }
    
    p = queue->head;
    sprintf(buffer, "QUEUE (%d) :", length(queue));
    printf("%s", buffer);
    while (p != NULL)
    {
        printf("%2c", p->info);
        p = p->link;
    }

    printf("\n");
    return 1;
}

